package org.springblade.modules.platform.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.modules.platform.algorithm.*;
import org.springblade.modules.platform.dto.AddEquipmentRuningState;
import org.springblade.modules.platform.dto.DeviceRuningStateDTO;
import org.springblade.modules.platform.entity.*;
import org.springblade.modules.platform.props.HuatengProperties;
import org.springblade.modules.platform.service.*;
import org.springblade.modules.platform.utils.TimeUtils;
import org.springblade.modules.platform.vo.AbsoluteValueVO;
import org.springblade.modules.platform.vo.GamaValueVO;
import org.springblade.modules.platform.vo.MeasuringChainDetailsVO;
import org.springblade.modules.platform.vo.MeasuringPlatformVO;
import org.springblade.modules.platform.websocket.config.WebSokcetChannelGroup;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@AllArgsConstructor
@RequestMapping("/service-huateng-sxdb/active")
@Api(value = "", tags = "主动查询")
@Slf4j
public class ActiveQueryController {
    private static RestTemplate restTemplate = new RestTemplate();
    private final HuatengProperties huatengProperties;
    private final IMeasuringPointTableService iMeasuringPointTableService;
    private final BaseStation4 baseStation4;
	private final BaseStation5 baseStation5;
	private final BaseStation6 baseStation6;
	private final BaseStation7 baseStation7;
	private final BladeRedis bladeRedis;
	private final IDeviceTableService iDeviceTableService;
	private final IMeasuringPlatformTypeService iMeasuringPlatformTypeService;
	private final BaseStation9 baseStation9;
	private final BaseStation10 baseStation10;
	private final BaseStation11 baseStation11;
	private final BaseStation12 baseStation12;
	private final IArcsecondTableService iArcsecondTableService;
	private final BaseStation13 baseStation13;
	private final BaseStation14 baseStation14;
	private final INoticeTableService iNoticeTableService;
	private final BaseStation15 baseStation15;
	private final BaseStation17 baseStation17;
	private final BaseStation18 baseStation18;
	private final BaseStation20 baseStation20;
	private final BaseStation21 baseStation21;
	private final BaseStation22 baseStation22;
	private final BaseStation23 baseStation23;
	private final BaseStation28 baseStation28;
	private final BaseStation29 baseStation29;
	private final BaseStation27 baseStation27;
    private static final AttributeKey<String> CONNECTION_ID = AttributeKey.valueOf("connectionId");
	private final BaseStation30 baseStation30;
	private final BaseStation31 baseStation31;
	private final BaseStation32 baseStation32;
	private final BaseStation33 baseStation33;
	private final BaseStation34 baseStation34;
	private final BaseStation35  baseStation35;
	private final BaseStation36  baseStation36;
	private final BaseStation37  baseStation37;
	private final BaseStation38  baseStation38;
	private final BaseStation39  baseStation39;
	private final CalculationMethod calculationMethod;
	private final CalculationMethod2 calculationMethod2;

	public static final Map<String,Double> map_9 = new HashMap<String,Double>(){{
		put("2024/02/03",0.0);
		put("2024/02/04",0.05);
		put("2024/02/05",0.02);
		put("2024/02/06",0.03);
		put("2024/02/07",-0.03);
		put("2024/02/08",0.11);
		put("2024/02/09",0.31);
		put("2024/02/10",0.28);
		put("2024/02/11",0.46);
		put("2024/02/12",0.54);
		put("2024/02/13",0.5);
		put("2024/02/14",0.52);
		put("2024/02/15",0.5);
		put("2024/02/16",0.42);
		put("2024/02/17",0.38);
		put("2024/02/18",0.49);
		put("2024/02/19",0.59);
		put("2024/02/20",0.7);
		put("2024/02/21",0.74);
		put("2024/02/22",0.75);
		put("2024/02/23",0.83);
		put("2024/02/24",0.9);
		put("2024/03/04",0.67);
		put("2024/03/05",0.68);
		put("2024/03/06",0.64);
		put("2024/03/07",0.64);
		put("2024/03/08",0.61);
		put("2024/03/09",0.71);
		put("2024/03/10",0.65);
		put("2024/03/14",0.15);
		put("2024/03/15",0.14);
		put("2024/03/27",-0.64);
		put("2024/03/28",-0.39);
		put("2024/03/29",-0.53);
		put("2024/03/30",-0.63);
		put("2024/04/02",-0.77);
		put("2024/04/03",-0.79);
		put("2024/04/04",-0.86);
		put("2024/04/05",-1.01);
		put("2024/04/06",-0.98);
		put("2024/04/07",-1.12);
		/*put("2024/04/12",-1.37);*/
		put("2024/04/13",-1.4);
		put("2024/04/14",-1.45);
		put("2024/05/24",-4.01);
		put("2024/05/25",-4.02);
		put("2024/05/26",-3.98);

	}};


    @GetMapping("/query")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "主动查询", notes = "测台ID")
    public R getQuery(@RequestParam(value = "startTime",required = false) Long startDate,
                      @RequestParam(value = "endTime",required = false) Long endDate) {
		Object o = bladeRedis.get("ACTIVE_QUERY");
		if(o!=null){
			return R.fail("数据正在同步中");

		}
		bladeRedis.set("ACTIVE_QUERY",1);
        String readManyDevice = huatengProperties.getReadManyDevice();
        MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
        if(startDate!=null&&endDate!=null){
            multiValueMap.add("endDate", TimeUtils.timeStampConversionTime(endDate,"yyyy-MM-dd HH:mm:ss"));
            multiValueMap.add("startDate",TimeUtils.timeStampConversionTime(startDate,"yyyy-MM-dd HH:mm:ss"));
        }
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(multiValueMap,new HttpHeaders());
        ResponseEntity<String> exchange = restTemplate.exchange(readManyDevice, HttpMethod.POST, httpEntity, String.class);
        log.info("主动查询响应:{}",exchange);
        String body = exchange.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        String date = jsonObject.get("data").toString();
        List<DeviceRuningStateDTO> list = JSONArray.parseArray(date, DeviceRuningStateDTO.class);
        List<MeasuringPointTable> measuringPointTables = iMeasuringPointTableService.selectByTime(startDate,endDate);
        if(!CollectionUtils.isEmpty(measuringPointTables)){
            List<Long> collect = measuringPointTables.stream().map(MeasuringPointTable::getGatherTime).collect(Collectors.toList());
            List<DeviceRuningStateDTO> collect1 = list.stream().filter(x -> !collect.contains(x.getAcquisitionTime())).collect(Collectors.toList());
			calculationMethod2.getDeviceRuningState(collect1,1);
        }else {
			//s6(list);
			//calculationMethod.getDeviceRuningState(list,1);
			calculationMethod2.getDeviceRuningState(list,1);
			//s32(list);
        }
		bladeRedis.del("ACTIVE_QUERY");
        return R.success("查询成功");
    }

	public void s33 (List<DeviceRuningStateDTO> list){
		List<DeviceRuningStateDTO> collect = list.stream().map(this::sl).filter(Objects::nonNull).collect(Collectors.toList());
		List<DeviceRuningStateDTO> deviceRuningStateDTOS = sl2(collect);
		deviceRuningStateDTOS.forEach(x->{
			baseStation39.installDeviceRuningState(x, x.getGatherEvent());
		});


	}
	public void s32 (List<DeviceRuningStateDTO> list){
		List<DeviceRuningStateDTO> collect = list.stream().map(this::sl).filter(Objects::nonNull).collect(Collectors.toList());
		List<DeviceRuningStateDTO> deviceRuningStateDTOS = sl2(collect);
		Integer measuringTypeCode = 1;

		for (DeviceRuningStateDTO x : deviceRuningStateDTOS) {
			String s = TimeUtils.timeStampConversionTime(x.getAcquisitionTime(), "yyyy/MM/dd");
			if(!map_9.containsKey(s)){
				continue;
			}
			for (int finalI = -400; finalI <= 400; finalI = finalI+10) {
				baseStation35.installDeviceRuningState(x, x.getGatherEvent(),finalI ,measuringTypeCode);
			}
			List<ArcsecondTable> list2 = iArcsecondTableService.list(Wrappers.<ArcsecondTable>lambdaQuery()
				.eq(ArcsecondTable::getGatherTime, x.getAcquisitionTime())
				.eq(ArcsecondTable::getMeasuringeCode, measuringTypeCode)
				.eq(ArcsecondTable::getType, 1)
				.eq(ArcsecondTable::getArcsecondType, 1));
			if(Func.isNotEmpty(list2)){
				ArcsecondTable arcsecondTable = list2.stream()
					.min(Comparator.comparingDouble(obj -> Math.abs(obj.getDifferenceValue()))).orElse(null);
				Float arcsecondValue = arcsecondTable.getArcsecondValue();
				for (Float finalI = arcsecondValue-0.5f; finalI <= 0.5f+arcsecondValue; finalI = finalI+0.1f) {
					baseStation38.installDeviceRuningState(x, x.getGatherEvent(),finalI ,measuringTypeCode);
				}
			}
			baseStation36.installDeviceRuningState(x, x.getGatherEvent() ,measuringTypeCode);
		}
		 measuringTypeCode = 2;
		for (DeviceRuningStateDTO x : deviceRuningStateDTOS) {
			String s = TimeUtils.timeStampConversionTime(x.getAcquisitionTime(), "yyyy/MM/dd");
			if(!map_9.containsKey(s)){
				continue;
			}
			for (int finalI = -400; finalI <= 400; finalI = finalI+10) {
				baseStation35.installDeviceRuningState(x, x.getGatherEvent(),finalI ,measuringTypeCode);
			}
			List<ArcsecondTable> list2 = iArcsecondTableService.list(Wrappers.<ArcsecondTable>lambdaQuery()
				.eq(ArcsecondTable::getGatherTime, x.getAcquisitionTime())
				.eq(ArcsecondTable::getMeasuringeCode, measuringTypeCode)
				.eq(ArcsecondTable::getType, 1)
				.eq(ArcsecondTable::getArcsecondType, 1));
			if(Func.isNotEmpty(list2)){
				ArcsecondTable arcsecondTable = list2.stream()
					.min(Comparator.comparingDouble(obj -> Math.abs(obj.getDifferenceValue()))).orElse(null);
				Float arcsecondValue = arcsecondTable.getArcsecondValue();
				for (Float finalI = arcsecondValue-0.5f; finalI <= 0.5f+arcsecondValue; finalI = finalI+0.1f) {
					baseStation38.installDeviceRuningState(x, x.getGatherEvent(),finalI ,measuringTypeCode);
				}
			}
			baseStation36.installDeviceRuningState(x, x.getGatherEvent() ,measuringTypeCode);
		}
	}
	/**
	 * 最终的Z
	 * @param list
	 */
	public void s11 (List<DeviceRuningStateDTO> list){
		List<DeviceRuningStateDTO> collect = list.stream().map(this::sl).filter(Objects::nonNull).collect(Collectors.toList());
		List<DeviceRuningStateDTO> deviceRuningStateDTOS = sl2(collect);
		deviceRuningStateDTOS.forEach(x-> {
			for (int finalI = -400; finalI <= 50; finalI = finalI+50) {
				baseStation33.installDeviceRuningState(x, x.getGatherEvent(),2,finalI,2 );
			}
			baseStation34.installDeviceRuningState(x,x.getGatherEvent());
		});
	}

	public void s10 (List<DeviceRuningStateDTO> list){
		List<DeviceRuningStateDTO> collect = list.stream().map(this::sl).filter(Objects::nonNull).collect(Collectors.toList());
		collect.forEach(x-> {
			List<MeasuringChainDetailsVO> measuringChainDetailsVOS = baseStation28.installDeviceRuningState(x, x.getGatherEvent());
			MeasuringChainDetailsVO measuringChainDetailsVO = measuringChainDetailsVOS.stream().filter(l -> l.getMeasurChainDirection() == 2).findFirst().get();
			List<MeasuringPlatformVO> measuringPlatformVOS = measuringChainDetailsVO.getMeasuringPlatformVOS();
			MeasuringPlatformVO measuringPlatformVO = measuringPlatformVOS.stream().filter(l1 -> l1.getMeasuringPlatformId() == 1701072301627441154L).findFirst().get();
			AbsoluteValueVO absoluteValueVO = measuringPlatformVO.getAbsoluteValueVO();

			Double z = absoluteValueVO.getZ();//逆向的Z
			for (double i = -5.0; i <= 5.0; i++) {
				double v = z + i / 10;
				baseStation29.installDeviceRuningState(x,x.getGatherEvent(),v,i);

			}
			List<ArcsecondTable> arcsecondTables = iArcsecondTableService.list(Wrappers.<ArcsecondTable>lambdaQuery()
				.eq(ArcsecondTable::getGatherTime, x.getAcquisitionTime())
				.eq(ArcsecondTable::getMeasuringPlatformId, 1701073023425216514L)
				.eq(ArcsecondTable::getMeasuringeCode, 1)
				.eq(ArcsecondTable::getType, 4));
			ArcsecondTable arcsecondTable = arcsecondTables.stream()
				.min(Comparator.comparingDouble(obj -> Math.abs(obj.getForwardValue()))).orElse(null);

			MeasuringPlatformVO measuringPlatformVO1 = baseStation31.installDeviceRuningState(x, x.getGatherEvent(), 0, arcsecondTable.getForwardValue());
			if(measuringPlatformVO1!=null){
				Double z1 = measuringPlatformVO1.getAbsoluteValueVO().getZ();

				if(Math.abs(z1)>Math.abs(z)){//扫描zhengx
					for (int i = -5; i <= 5; i++) {
						baseStation30.installDeviceRuningState(x,x.getGatherEvent(),i,z,1,i);
					}
				}else if(Math.abs(z1)<Math.abs(z)){
					for (int i = -5; i <= 5; i++) {
						baseStation30.installDeviceRuningState(x,x.getGatherEvent(),i,0.0,2,i);
					}
				}

			}
			baseStation32.installDeviceRuningState(x,x.getGatherEvent(), arcsecondTable.getForwardValue());
		});

	}

	public void s9 (List<DeviceRuningStateDTO> list){
		List<DeviceRuningStateDTO> collect = list.stream().map(this::sl).filter(Objects::nonNull).collect(Collectors.toList());
		collect.forEach(x-> baseStation27.installDeviceRuningState(x,x.getGatherEvent()));

	}
	public void s (List<DeviceRuningStateDTO> list){
		List<DeviceRuningStateDTO> collect = list.stream().map(this::sl).filter(Objects::nonNull).collect(Collectors.toList());

		for (double i = -5.0; i <= 5.0; i++) {
			Double finalI = i;

			collect.forEach(x-> baseStation6.installDeviceRuningState(x,x.getGatherEvent(),1, finalI));
		}
		log.info("第一次计算完成");


		for (int i = -6; i <= 10; i = i+2) {
			Integer finalI = i;
			collect.forEach(x-> baseStation5.installDeviceRuningState(x,x.getGatherEvent(),2, finalI));
		}
		for (DeviceRuningStateDTO x : collect) {
			List<ArcsecondTable> arcsecondTables = iArcsecondTableService.list(Wrappers.<ArcsecondTable>lambdaQuery()
				.eq(ArcsecondTable::getGatherTime, x.getAcquisitionTime())
				.eq(ArcsecondTable::getType, 1)
				.eq(ArcsecondTable::getMeasuringeCode, 2)
				.eq(ArcsecondTable::getArcsecondType, 2));

			ArcsecondTable arcsecondTable = arcsecondTables.stream()
				.min(Comparator.comparingDouble(obj -> Math.abs(obj.getDifferenceValue()))).orElse(null);
			if(arcsecondTable.getDifferenceValue()>0.2||arcsecondTable.getDifferenceValue()<-0.2){
				for (double finalI = -2.0; finalI <= 6.0; finalI = finalI+0.5) {
					baseStation9.installDeviceRuningState(x, x.getGatherEvent(), 2, finalI, arcsecondTable);
				}

			}
		}
		collect.forEach(x-> baseStation7.installDeviceRuningState(x,x.getGatherEvent()));


	}

	/**
	 * x最终扫描
	 * @param list
	 */
	public void s6 (List<DeviceRuningStateDTO> list){
		bladeRedis.del("GAME:" + 1);
		bladeRedis.del("GAME:" + 2);
		bladeRedis.del("acquisitionTime:");
		List<DeviceRuningStateDTO> collect = list.stream().map(this::sl).filter(Objects::nonNull).collect(Collectors.toList());
		/*List<DeviceRuningStateDTO> deviceRuningStateDTOS = sl2(collect);*/
		for (DeviceRuningStateDTO x : collect) {
			/**
			 * 扫Z
			 */
			for (int finalI = -400; finalI <= 50; finalI = finalI+50) {
				baseStation33.installDeviceRuningState(x, x.getGatherEvent(),2,finalI,2 );
			}


			Object o = bladeRedis.get("GAME:" + 1);
			Object o2 = bladeRedis.get("GAME:" + 2);
			if(o==null&&o2==null){//第一次进来出事伽马为0
				bladeRedis.set("GAME:" + 1,0.0);
				bladeRedis.set("GAME:" + 2,0.0);
				//baseStation11.installDeviceRuningState(x, x.getGatherEvent(), 2, 0.0,null,null);
				baseStation21.installDeviceRuningState(x,x.getGatherEvent());

			}else {
				GamaValueVO gamaValueVO = baseStation22.installDeviceRuningState(x, x.getGatherEvent(), 2, null);//比较大小
				if(gamaValueVO.getValue()>gamaValueVO.getNvalue()){//正向大于逆向
					for (int finalI = -20; finalI <= 20; finalI = finalI+1) {
						baseStation23.installDeviceRuningState(x, x.getGatherEvent(), 2, finalI,1);//8侧台
					}
					//baseStation11.installDeviceRuningState(x, x.getGatherEvent(), 2, 0.0,null,null);
					baseStation21.installDeviceRuningState(x,x.getGatherEvent());
				}else {
					for (int finalI = -20; finalI <= 20; finalI = finalI+1) {
						baseStation23.installDeviceRuningState(x, x.getGatherEvent(), 2, finalI,2);//8侧台
					}


 					baseStation21.installDeviceRuningState(x,x.getGatherEvent());
				}
			}
		}
	}

	public void s4 (List<DeviceRuningStateDTO> list){
		List<DeviceRuningStateDTO> collect = list.stream().map(this::sl).filter(Objects::nonNull).collect(Collectors.toList());

		for (DeviceRuningStateDTO x : collect) {
			//baseStation13.installDeviceRuningState(x,x.getGatherEvent(),null);

			baseStation15.installDeviceRuningState(x, x.getGatherEvent(), 2, 0.0,null);
			List<ArcsecondTable> list1 = iArcsecondTableService.list(Wrappers.<ArcsecondTable>lambdaQuery()
				.eq(ArcsecondTable::getGatherTime, x.getAcquisitionTime())
				.eq(ArcsecondTable::getType, 3)
				.eq(ArcsecondTable::getArcsecondType, 2));
			if(!CollectionUtils.isEmpty(list1)){
				ArcsecondTable arcsecondTablen = list1.stream().filter(li -> li.getMeasuringeCode() == 2).findFirst().get();
				ArcsecondTable arcsecondTablez = list1.stream().filter(li -> li.getMeasuringeCode() == 1).findFirst().get();

				Double reverseValue = arcsecondTablen.getReverseValue();//逆向
				Double forwardValue = arcsecondTablez.getForwardValue();//正向
				Object o = bladeRedis.get("GAME:" + 1);
				Object o2 = bladeRedis.get("GAME:" + 2);
				if(forwardValue>reverseValue){//正向大于逆向

					if(o==null){//第一次进来
						bladeRedis.set("GAME:"+ 1,0.0);
					}else {
						double v = Double.parseDouble(o.toString());
						double s = v-0;
						double e = v+1.5;
						for (double finalI = s; finalI <= e; finalI = finalI+0.1) {
							baseStation14.installDeviceRuningState(x, x.getGatherEvent(), 2, finalI,1,1701072223391088642L);
						}

					}
					if(o2==null){//第一次进来
						bladeRedis.set("GAME:"+ 2,0.0);
					}else {
						double v = Double.parseDouble(o2.toString());
						double s = v-0;
						double e = v+1.5;
						for (double finalI = s; finalI <= e; finalI = finalI+0.1) {
							baseStation14.installDeviceRuningState(x, x.getGatherEvent(), 2, finalI,2,1701072223391088642L);
						}
					}
					baseStation11.installDeviceRuningState(x, x.getGatherEvent(), 2, 0.0,null,null);
					baseStation13.installDeviceRuningState(x,x.getGatherEvent(),null);
				}else 	if(forwardValue<reverseValue){
					if(o==null){//第一次进来
						bladeRedis.set("GAME:"+ 1,0.0);
					}else {
						double v = Double.parseDouble(o.toString());
						double s = v-1.5;
						double e = v+0;
						for (double finalI = s; finalI <= e; finalI = finalI+0.1) {
							baseStation14.installDeviceRuningState(x, x.getGatherEvent(), 2, finalI,1,1701072223391088642L);
						}

					}
					if(o2==null){//第一次进来
						bladeRedis.set("GAME:"+ 2,0.0);
					}else {
						double v = Double.parseDouble(o2.toString());
						double s = v-1.5;
						double e = v+0;
						for (double finalI = s; finalI <= e; finalI = finalI+0.1) {
							baseStation14.installDeviceRuningState(x, x.getGatherEvent(), 2, finalI,2,1701072223391088642L);
						}
					}
					baseStation11.installDeviceRuningState(x, x.getGatherEvent(), 2, 0.0,null,null);
					baseStation13.installDeviceRuningState(x,x.getGatherEvent(),null);
				}else {
					baseStation11.installDeviceRuningState(x, x.getGatherEvent(), 2, 0.0,null,null);
					baseStation13.installDeviceRuningState(x,x.getGatherEvent(),null);
				}
			}
		}
	}
	public void s3 (List<DeviceRuningStateDTO> list){
		List<DeviceRuningStateDTO> collect = list.stream().map(this::sl).filter(Objects::nonNull).collect(Collectors.toList());

		for (DeviceRuningStateDTO x : collect) {
			Object o = bladeRedis.get("GAME:" + 1);
			Object o2 = bladeRedis.get("GAME:" + 2);
			if(o==null){//第一次进来
				bladeRedis.set("GAME:"+ 1,0.0);
			}else {
				double v = Double.parseDouble(o.toString());
				double s = v-3;
				double e = v+3;
				for (double finalI = s; finalI <= e; finalI = finalI+0.1) {
					baseStation14.installDeviceRuningState(x, x.getGatherEvent(), 2, finalI,1,null);
				}

			}
			if(o2==null){//第一次进来
				bladeRedis.set("GAME:"+ 2,0.0);
			}else {
				double v = Double.parseDouble(o2.toString());
				double s = v-3;
				double e = v+3;
				for (double finalI = s; finalI <= e; finalI = finalI+0.1) {
					baseStation14.installDeviceRuningState(x, x.getGatherEvent(), 2, finalI,2,null);
				}
			}
			baseStation11.installDeviceRuningState(x, x.getGatherEvent(), 2, 0.0,null,null);
			baseStation13.installDeviceRuningState(x,x.getGatherEvent(),null);
		}
	}
	public void s2 (List<DeviceRuningStateDTO> list){
		List<DeviceRuningStateDTO> collect = list.stream().map(this::sl).filter(Objects::nonNull).collect(Collectors.toList());
		for (double i = 5.0; i <= 10.0; i=i+0.2) {
			Double finalI = i;
			collect.forEach(x-> baseStation6.installDeviceRuningState(x,x.getGatherEvent(),2, finalI));
		}
		log.info("第一次计算完成");
		for (DeviceRuningStateDTO x : collect) {
			List<ArcsecondTable> arcsecondTables = iArcsecondTableService.list(Wrappers.<ArcsecondTable>lambdaQuery()
				.eq(ArcsecondTable::getGatherTime, x.getAcquisitionTime())
				.eq(ArcsecondTable::getMeasuringeCode, 2)
				.eq(ArcsecondTable::getType, 1)
				.eq(ArcsecondTable::getArcsecondType, 2));
			ArcsecondTable arcsecondTable = arcsecondTables.stream()
				.min(Comparator.comparingDouble(obj -> Math.abs(obj.getDifferenceValue()))).orElse(null);
			if(arcsecondTable.getDifferenceValue()>0.2||arcsecondTable.getDifferenceValue()<-0.2){
				for (double finalI = 0.8; finalI <= 6; finalI = finalI+0.2) {
					baseStation9.installDeviceRuningState(x, x.getGatherEvent(), 2, finalI, arcsecondTable);
				}

			}
		}
		for (DeviceRuningStateDTO x : collect) {
			List<ArcsecondTable> list111 = iArcsecondTableService.list(Wrappers.<ArcsecondTable>lambdaQuery()
				.eq(ArcsecondTable::getGatherTime,  x.getAcquisitionTime())
				.eq(ArcsecondTable::getMeasuringeCode, 2)
				.eq(ArcsecondTable::getType, 1)
				.eq(ArcsecondTable::getArcsecondType, 2));
			ArcsecondTable arcsecondTable = list111.stream()
				.min(Comparator.comparingDouble(obj -> Math.abs(obj.getDifferenceValue()))).orElse(null);
			ArcsecondTable arcsecondTable1 = list111.stream()
				.max(Comparator.comparingDouble(obj -> Math.abs(obj.getArcsecondValue()))).orElse(null);

			if(Objects.equals(arcsecondTable.getArcsecondValue(), arcsecondTable1.getArcsecondValue())){
				baseStation6.installDeviceRuningState(x,x.getGatherEvent(),2, arcsecondTable.getArcsecondValue()+0.2);
			}
			List<ArcsecondTable> list1112 = iArcsecondTableService.list(Wrappers.<ArcsecondTable>lambdaQuery()
				.eq(ArcsecondTable::getGatherTime,  x.getAcquisitionTime())
				.eq(ArcsecondTable::getMeasuringeCode, 1)
				.eq(ArcsecondTable::getType, 1)
				.eq(ArcsecondTable::getArcsecondType, 2));
			if(Func.isNotEmpty(list1112)){
				ArcsecondTable arcsecondTable12 = list1112.stream()
					.min(Comparator.comparingDouble(obj -> Math.abs(obj.getDifferenceValue()))).orElse(null);

				ArcsecondTable arcsecondTable13 = list1112.stream()
					.max(Comparator.comparingDouble(obj -> Math.abs(obj.getArcsecondValue()))).orElse(null);

				if(Objects.equals(arcsecondTable12.getArcsecondValue(), arcsecondTable13.getArcsecondValue())){
					baseStation9.installDeviceRuningState(x,x.getGatherEvent(),2, Double.parseDouble(arcsecondTable13.getArcsecondValue()+"")+0.2,arcsecondTable12);
				}
			}
		}
		for (DeviceRuningStateDTO x : collect) {
			List<ArcsecondTable> list111 = iArcsecondTableService.list(Wrappers.<ArcsecondTable>lambdaQuery()
				.eq(ArcsecondTable::getGatherTime,  x.getAcquisitionTime())
				.eq(ArcsecondTable::getMeasuringeCode, 2)//逆向
				.eq(ArcsecondTable::getType, 1)
				.eq(ArcsecondTable::getArcsecondType, 2));
			ArcsecondTable arcsecondTable = list111.stream()
				.min(Comparator.comparingDouble(obj -> Math.abs(obj.getDifferenceValue()))).orElse(null);

			List<ArcsecondTable> list1112 = iArcsecondTableService.list(Wrappers.<ArcsecondTable>lambdaQuery()
				.eq(ArcsecondTable::getGatherTime,  x.getAcquisitionTime())
				.eq(ArcsecondTable::getMeasuringeCode, 1)
				.eq(ArcsecondTable::getType, 1)
				.eq(ArcsecondTable::getArcsecondType, 2));
			ArcsecondTable arcsecondTable12 = null;
			if(Func.isNotEmpty(list)){
				 arcsecondTable12 = list1112.stream()
					.min(Comparator.comparingDouble(obj -> Math.abs(obj.getDifferenceValue()))).orElse(null);

			}
			baseStation11.installDeviceRuningState(x, x.getGatherEvent(), 2, 0.0, arcsecondTable,arcsecondTable12);
		/*	for (double finalI = -4.0; finalI <= 0.0;finalI = finalI+0.2) {

				baseStation10.installDeviceRuningState(x, x.getGatherEvent(), 2, finalI, arcsecondTable,arcsecondTable12);
			}*/
		}



		collect.forEach(x-> baseStation7.installDeviceRuningState(x,x.getGatherEvent()));
	}
	public List<DeviceRuningStateDTO> sl2(List<DeviceRuningStateDTO> deviceRuningStateDTO){

	return 	deviceRuningStateDTO.stream().filter(x->TimeUtils.getDateTimeOfTimestamp(x.getAcquisitionTime()).getHour()==4
		&&TimeUtils.getDateTimeOfTimestamp(x.getAcquisitionTime()).getMinute()<32).collect(Collectors.toList());
	}
	public DeviceRuningStateDTO sl(DeviceRuningStateDTO deviceRuningStateDTO){
/*		Long acquisitionTime = deviceRuningStateDTO.getAcquisitionTime();//采集时间
		Object o = bladeRedis.get("acquisitionTime:");
		if(o==null){
			bladeRedis.set("acquisitionTime:",acquisitionTime);
		}else {
			if((acquisitionTime-Long.parseLong(o.toString())>(1000*60*60*2))){
				bladeRedis.set("acquisitionTime:",acquisitionTime);
				return null;
			}
		}
		bladeRedis.set("acquisitionTime:",acquisitionTime);*/
	/*		Long acquisitionTime = deviceRuningStateDTO.getAcquisitionTime();//采集时间
		Object o = bladeRedis.get("acquisitionTime:");
		if(o==null){
			bladeRedis.set("acquisitionTime:",acquisitionTime);
		}else {
			if((acquisitionTime-Long.parseLong(o.toString())>(1000*60*60*2))){
				bladeRedis.set("acquisitionTime:",acquisitionTime);
				return null;
			}
		}
		bladeRedis.set("acquisitionTime:",acquisitionTime);*/
		for (DeviceRuningStateDTO.DeviceListDTO x : deviceRuningStateDTO.getDeviceList()) {
			List<DeviceRuningStateDTO.DeviceListDTO.AttributeListDTO> attributeListDTO = x.getAttributeListDTO();
			if(attributeListDTO.stream().map(DeviceRuningStateDTO.DeviceListDTO.AttributeListDTO::getKey).collect(Collectors.toList()).contains("real_value")){
				continue;

			}
			Optional<DeviceRuningStateDTO.DeviceListDTO.AttributeListDTO> ccd2AfterDipY1 = attributeListDTO.stream().filter(l -> l.getKey().equalsIgnoreCase("ccd2_after_dip_y")).findFirst();
			if(!ccd2AfterDipY1.isPresent()){
				continue;
			}
			Optional<DeviceRuningStateDTO.DeviceListDTO.AttributeListDTO> ccd2FrontDipY1 = attributeListDTO.stream().filter(l -> l.getKey().equalsIgnoreCase("ccd2_front_dip_y")).findFirst();
			if(!ccd2FrontDipY1.isPresent()){
				continue;
			}

			DeviceRuningStateDTO.DeviceListDTO.AttributeListDTO ccd2AfterDipY = ccd2AfterDipY1.get();
			DeviceRuningStateDTO.DeviceListDTO.AttributeListDTO ccd2FrontDipY = ccd2FrontDipY1.get();

			if((ccd2AfterDipY.getValue()>7000||(ccd2AfterDipY.getValue()<=500&&ccd2AfterDipY.getValue()>0))&&
				(ccd2FrontDipY.getValue()>7000||(ccd2FrontDipY.getValue()<=500&&ccd2FrontDipY.getValue()>0))
			){
				DeviceTable one = iDeviceTableService.lambdaQuery()
					.eq(DeviceTable::getDeviceChannelId, x.getDeviceId())
					.eq(DeviceTable::getIsDeleted, 0).one();
				MeasuringPlatformType one1 = iMeasuringPlatformTypeService.getOne(Wrappers.<MeasuringPlatformType>lambdaQuery().like(MeasuringPlatformType::getDeviceId, one.getDeviceId()));
				NoticeTable noticeTable = new NoticeTable();
				noticeTable.setState(2);
				noticeTable.setEquipmentName(one1.getMeasuringPlatformName());
				noticeTable.setEquipmentId( x.getDeviceId());
				noticeTable.setGatherTime(deviceRuningStateDTO.getAcquisitionTime());
				noticeTable.setAlarmContent("CCD异常:"+ccd2AfterDipY.getKey()+":"+ccd2AfterDipY.getValue()+"||"+ccd2FrontDipY.getKey()+":"+ccd2FrontDipY.getValue());
				iNoticeTableService.save(noticeTable);
				return null;
			}
			Integer ccd1_x_after_backward = attributeListDTO.stream().filter(l -> l.getKey().equalsIgnoreCase("ccd1_x_after_backward")).findFirst().get().getValue();
			Integer ccd1_x_front_backward = attributeListDTO.stream().filter(l -> l.getKey().equalsIgnoreCase("ccd1_x_front_backward")).findFirst().get().getValue();
			Integer ccd4_x_after_backward = attributeListDTO.stream().filter(l -> l.getKey().equalsIgnoreCase("ccd4_x_after_backward")).findFirst().get().getValue();
			Integer ccd4_x_front_backward = attributeListDTO.stream().filter(l -> l.getKey().equalsIgnoreCase("ccd4_x_front_backward")).findFirst().get().getValue();

			if(!((ccd1_x_after_backward<7000&&ccd1_x_front_backward<7000&&ccd4_x_after_backward<7000&&ccd4_x_front_backward<7000)
				||(ccd1_x_front_backward>7000&&ccd4_x_front_backward>7000&&ccd1_x_after_backward<7000&&ccd4_x_after_backward<7000)
				||(ccd1_x_front_backward<7000&&ccd4_x_front_backward<7000&&ccd1_x_after_backward>7000&&ccd4_x_after_backward>7000)
			)){
				DeviceTable one = iDeviceTableService.lambdaQuery()
					.eq(DeviceTable::getDeviceChannelId, x.getDeviceId())
					.eq(DeviceTable::getIsDeleted, 0).one();
				MeasuringPlatformType one1 = iMeasuringPlatformTypeService.getOne(Wrappers.<MeasuringPlatformType>lambdaQuery().like(MeasuringPlatformType::getDeviceId, one.getDeviceId()));
				NoticeTable noticeTable = new NoticeTable();
				noticeTable.setState(2);
				noticeTable.setEquipmentName(one1.getMeasuringPlatformName());
				noticeTable.setEquipmentId( x.getDeviceId());
				noticeTable.setGatherTime(deviceRuningStateDTO.getAcquisitionTime());
				noticeTable.setAlarmContent("CCD异常:"+ccd2AfterDipY.getKey()+":"+ccd2AfterDipY.getValue()+"||"+ccd2FrontDipY.getKey()+":"+ccd2FrontDipY.getValue());
				iNoticeTableService.save(noticeTable);
				return null;
			}
/*			for (DeviceRuningStateDTO.DeviceListDTO.AttributeListDTO y : attributeListDTO) {

				if(!y.getKey().equalsIgnoreCase("electricity")&&!y.getKey().equalsIgnoreCase("temperature")){
					if(y.getValue()>7000||(y.getValue()<=500&&y.getValue()>0)){
						DeviceTable one = iDeviceTableService.lambdaQuery()
							.eq(DeviceTable::getDeviceChannelId, x.getDeviceId())
							.eq(DeviceTable::getIsDeleted, 0).one();
						NoticeTable noticeTable = new NoticeTable();
						noticeTable.setState(2);
						noticeTable.setEquipmentName(one.getDeviceName());
						noticeTable.setEquipmentId( x.getDeviceId());
						noticeTable.setGatherTime(deviceRuningStateDTO.getAcquisitionTime());
						noticeTable.setAlarmContent("CCD异常:"+y.getKey()+":"+y.getValue());
						iNoticeTableService.save(noticeTable);
						return null;
					}
				}

			}*/
		}


		return deviceRuningStateDTO;
	}

    @PostMapping("/report")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "上报", notes = "上报")
      public R report(@RequestBody List<DeviceRuningStateDTO> list) {
		calculationMethod2.getDeviceRuningState(list,2);
        return R.success("成功");
    }
    @GetMapping("/Queries/{chainId}")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "主动查询", notes = "上报")
    public R Queries(@PathVariable Long chainId) {
        String readMeasureChainDataWithStandardPressure = huatengProperties.getReadMeasureChainDataWithStandardPressure() + chainId;
        ResponseEntity<AddEquipmentRuningState> forEntity = restTemplate.getForEntity(readMeasureChainDataWithStandardPressure, AddEquipmentRuningState.class);
        AddEquipmentRuningState body = forEntity.getBody();
        log.info("主动查询响应:{}",body);
        return R.success("成功");
    }

    @PostMapping("/schedule")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "进度条", notes = "进度条")
    public void pullData(@RequestBody JSONObject jsonObject){
        log.info("推送数据:{}",JSONObject.toJSONString(jsonObject));
        ChannelGroup channels = WebSokcetChannelGroup.channels;
        Map<String, List<String>> map = WebSokcetChannelGroup.MAP;
        if(map.containsKey("COLLECT_DATA")){
            List<String> stringList = map.get("COLLECT_DATA");
            if(Func.isEmpty(stringList)){
                return;
            }
            String connectionId = jsonObject.get("connectionId").toString();
            Optional<Channel> first = channels.stream().filter(x ->x.attr(CONNECTION_ID).get().contains(connectionId)).findFirst();
            if(first.isPresent()){
                ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
                channelGroup.add(first.get());
                channelGroup.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(jsonObject)));
            }

        }
    }



}
